#!/bin/bash
function install_csvn() {
    echo "安装CSVN" >>$logs_file
    rm -rf /tmp/.csvn.err.info
    csvnHome="$workHome/packages/csvn"
    command -v ss >/dev/null 2>&1
    if [ "$?" == "0" ];then
        listen_cmd="ss -lnpt"
    else
        command -v netstat >/dev/null 2>&1
        if [ "$?" == "0" ];then
          listen_cmd="netstat -tnlp"
        fi
    fi
    [[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
    
    csvnPath=$(whiptail --backtitle "Author: Elvis" --title "csvn配置" --inputbox --nocancel \
    "请输入csvn安装目录" 10 60 "/usr/local" 3>&1 1>&2 2>&3)
    csvnPath=${csvnPath:-/usr/local}
    csvnPath=`echo $csvnPath`
    csvnPath=${csvnPath%/}
    isNull=`ls $csvnPath/csvn/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        whiptail --backtitle "Author: Elvis" --title "警告" --yes-button "继续" --no-button "退出" --yesno "$csvnPath目录下存在csvn文件夹，且不为空，继续安装会删除已有数据！\n\n是否继续安装？" 10 50
        if [ "$?" != "0" ];then
         sleep 0.10
         return 1
        fi
    fi
    
    csvnPort_control=
    PortUsed=
    PortUsed_Pro=
    while [[ ! "$csvnPort_control" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        csvnPort_control=$(whiptail --backtitle "Author: Elvis" --title "csvn配置" --inputbox --nocancel \
        "请输入csvn管理端口，请使用>1024的端口" 10 60 "3343" 3>&1 1>&2 2>&3)
        if [[ ! "$csvnPort_control" =~ ^[1-9][0-9]+$ ]];then
             whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "csvn管理端口只能为两位及以上且不以0开头的数字组成，请重新输入！" 10 60
             sleep 0.5
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${csvnPort_control} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "csvn管理端口已被使用，请重新输入！" 8 60
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    csvnPort_control=${csvnPort_control:-3343}
    csvnPort_control=`echo $csvnPort_control`
    
    csvnSSLPort_control=`expr $csvnPort_control + 1091`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${csvnSSLPort_control} "`
        while [[ -n $PortUsed_Pro ]]
        do
          csvnSSLPort_control=`expr $csvnSSLPort_control + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${csvnSSLPort_control} "`
        done
    fi

    csvnPort=
    PortUsed=
    PortUsed_Pro=
    while [[ ! "$csvnPort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        csvnPort=$(whiptail --backtitle "Author: Elvis" --title "csvn配置" --inputbox --nocancel \
        "请输入SVN服务端口，请使用>1024的端口，除非你使用80或者443端口" 10 60 "443" 3>&1 1>&2 2>&3)
        if [[ ! "$csvnPort" =~ ^[1-9][0-9]+$ ]];then
             whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "SVN服务端口只能为两位及以上且不以0开头的数字组成，请重新输入！" 10 60
             sleep 0.5
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null|grep ":${csvnPort} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "SVN服务端口已被使用，请重新输入！" 8 60
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    csvnPort=${csvnPort:-443}
    csvnPort=`echo $csvnPort`
    
    csvnUser=
    csvnUser=$(whiptail --backtitle "Author: Elvis" --title "csvn配置" --inputbox --nocancel \
    "请输入csvn运行用户" 10 60 "csvn" 3>&1 1>&2 2>&3)
    csvnUser=${csvnUser:-csvn}
    csvnUser=`echo $csvnUser`

    source /etc/profile >/dev/null 2>&1
    source ~/.bash_profile >/dev/null 2>&1
    source ~/.bashrc >/dev/null 2>&1
    javaPath=`command -v java`
    if [ -z "$javaPath" ];then
        javaPath=$(whiptail --backtitle "Author: Elvis" --title "JDK配置" --inputbox --nocancel \
    "系统未找到到java命令，请手动输入java命令路径" 10 60 "/usr/bin/java" 3>&1 1>&2 2>&3)
    else
        whiptail --backtitle "Author: Elvis" --title "警告" --yes-button "确定" --no-button "修改" --yesno "系统检测到java命令路径为$javaPath\n如果你的CSVN版本比较旧，建议使用JAVA7或6，新版本的JDK可能导致CSVN无法正常工作\n\n如果正确请确认，不正确请修改." 12 60
        if [ "$?" != "0" ];then
          javaPath=$(whiptail --backtitle "Author: Elvis" --title "JDK配置" --inputbox --nocancel "请输入java命令位置" 10 60 "/usr/bin/java" 3>&1 1>&2 2>&3)
        fi
    fi
    javaPath=`echo $javaPath`
    javaOut=`$javaPath -version 2>&1|grep 'version "'`
    if [ -z "$javaOut" ];then
        msg="设置的java命令路径错误，执行java -version命令错误，退出csvn安装"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "$msg" 10 70
        sleep 0.10
        return 1
    fi
    
    # java版本信息
    java_version=$($javaPath -version 2>&1|head -n 1)
    
    whiptail --backtitle "Author: Elvis" --title "csvn安装信息汇总" --yesno "\ncsvn安装位置：$csvnPath\ncsvn管理端口：$csvnPort_control\nSVN服务端口：$csvnPort\ncsvn运行用户：$csvnUser\nJAVA命令：$javaPath\nJDK版本信息：$java_version\n\nYes以继续安装，No退出csvn安装" 15 70
    if [ "$?" != "0" ];then
        sleep 0.10
        return 1
    fi
    csvnUserPw=`strings /dev/urandom |grep -o '[[:alnum:]_%@!]'|head -n 25|tr -d '\n'`
    
    {
    echo 1
    sleep 1
    msg="创建csvn运行用户"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n20\n$msg\nXXX"
    echo 20
    isExistU=`cat /etc/passwd|grep "^$csvnUser:"`
    if [ -z "$isExistU" ];then
        /usr/sbin/useradd $csvnUser >>$logs_file 2>&1
        echo "$csvnUserPw"|passwd --stdin $csvnUser >>$logs_file 2>&1
    else
        if [ "$csvnUser" != "root" ];then
         /usr/sbin/usermod -s /bin/bash $csvnUser >>$logs_file 2>&1 
         echo "$csvnUserPw"|passwd --stdin $csvnUser >>$logs_file 2>&1
        fi
    fi
    
    msg="开始安装csvn"
    rm -rf $csvnPath/csvn
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n40\n$msg\nXXX"
    echo 40
    if [ ! -d $csvnPath ];then
        mkdir -p $csvnPath >/dev/null 2>&1
        chown -R $csvnUser:$csvnUser $csvnPath >/dev/null 2>&1
    fi
    csvnPack=`ls -r $csvnHome/ 2>/dev/null |grep CollabNetSubversionEdge.*.tar.gz|head -n 1`
    cd $csvnHome
    tar zxf $csvnPack -C $csvnPath >/dev/null 2>>$logs_file
    if [ "$?" != "0" ];then
        msg="csvn安装包损坏，解压失败"
        echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
        echo -e "XXX\n45\n$msg\nXXX"
        echo "$msg" >/tmp/.csvn.err.info
        echo 45
        sleep 1
        return 1
    fi
    
    real_javaPath=$(readlink -f $javaPath)
    javaHome=${real_javaPath%%/bin/*}
    msg="初始化CSVN管理服务，此过程大概需要2分钟左右"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n60\n$msg\nXXX"
    echo 60
    cd $csvnPath/csvn/
    mkdir $csvnPath/csvn/tmp
    /bin/mv -f /etc/init.d/csvn /etc/init.d/csvn-1 >/dev/null 2>&1
    /bin/mv -f /etc/init.d/csvn-httpd /etc/init.d/csvn-httpd-1 >/dev/null 2>&1
    chkconfig csvn-1 on >/dev/null 2>&1
    chkconfig csvn-httpd-1 on >/dev/null 2>&1
    ./bin/csvn install >>$logs_file 2>&1
    sed -i "s#localhost:3343#$ipaddr:$csvnPort_control#g" $csvnPath/csvn/data/conf/csvn.conf >>$logs_file 2>&1
    sed -i "s#.*JAVA_HOME=.*#JAVA_HOME=$javaHome#g" $csvnPath/csvn/data/conf/csvn.conf >>$logs_file 2>&1
    sed -i "s/.*RUN_AS_USER=.*/RUN_AS_USER=$csvnUser/g" $csvnPath/csvn/data/conf/csvn.conf >>$logs_file 2>&1
    sed -i "s/Djetty.port=.*/Djetty.port=$csvnPort_control/g" $csvnPath/csvn/data/conf/csvn-wrapper.conf >>$logs_file 2>&1
    sed -i "s/Djetty.ssl.port=.*/Djetty.ssl.port=$csvnSSLPort_control/g" $csvnPath/csvn/data/conf/csvn-wrapper.conf >>$logs_file 2>&1
    cat >>$csvnPath/csvn/appserver/start.ini<<EOF
-Djava.io.tmpdir=$csvnPath/csvn/tmp
-Djava.library.path=$csvnPath/csvn/lib
EOF
    chown -R $csvnUser:$csvnUser $csvnPath/csvn/
    $csvnPath/csvn/bin/csvn install >/dev/null 2>&1
    $csvnPath/csvn/bin/csvn start >>$logs_file 2>&1
    curl -s -I --fail http://$ipaddr:$csvnPort_control/csvn >/dev/null 2>&1
    run_status="$?"
    n=0
    while [ "$run_status" != "0" ]
    do
        sleep 1
        let n+=1
        curl -s -I --fail http://$ipaddr:$csvnPort_control/csvn >/dev/null 2>&1
        run_status="$?"
        if [ $n -gt 15 ];then
            break
        fi
    done
    /etc/init.d/csvn stop >>$logs_file 2>&1
    $csvnPath/csvn/bin/csvn install >/dev/null 2>&1

    msg="修改SVN配置"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n80\n$msg\nXXX"
    echo 80
    $csvnPath/csvn/bin/csvn-httpd install >>$logs_file 2>&1
 
    /bin/cp -rf $csvnPath/csvn/data/certs/svnedge.crt $csvnPath/csvn/data/conf/server.crt >>$logs_file 2>&1
    /bin/cp -rf $csvnPath/csvn/data/certs/svnedge.key $csvnPath/csvn/data/conf/server.key >>$logs_file 2>&1
    #
    sed -i "/,'ServerSettings',/ s/0/1/g" $csvnPath/csvn/data/csvn-production-hsqldb.script >>$logs_file 2>&1
    sed -i "/,'ServerSettings',/ s/FALSE/TRUE/g" $csvnPath/csvn/data/csvn-production-hsqldb.script >>$logs_file 2>&1
    sed -i '/INSERT INTO SERVER VALUES/ s/(1,0/(1,1/g' $csvnPath/csvn/data/csvn-production-hsqldb.script >>$logs_file 2>&1
    sed -i "/INSERT INTO SERVER VALUES/ s/,18080,/,$csvnPort,/g" $csvnPath/csvn/data/csvn-production-hsqldb.script >>$logs_file 2>&1
    sed -i "/INSERT INTO SERVER VALUES/ s/,80,/,$csvnPort,/g" $csvnPath/csvn/data/csvn-production-hsqldb.script >>$logs_file 2>&1
    sed -i '/INSERT INTO SERVER VALUES/ s/FALSE,NULL,NULL,FALSE,FALSE/FALSE,NULL,NULL,TRUE,FALSE/g' $csvnPath/csvn/data/csvn-production-hsqldb.script >>$logs_file 2>&1
    hostName=`hostname`
    sed -i "/INSERT INTO SERVER VALUES/ s/$hostName/$ipaddr/g" $csvnPath/csvn/data/csvn-production-hsqldb.script >>$logs_file 2>&1
    
    #密码强度
    sed -i 's/^password.policy.strong=.*/password.policy.strong=false/g' $csvnPath/csvn/data/conf/security.properties >/dev/null 2>&1
    sed -i 's/^password.policy.min.length=.*/password.policy.min.length=6/g' $csvnPath/csvn/data/conf/security.properties >/dev/null 2>&1
    
    chown -R $csvnUser:$csvnUser $csvnPath/csvn/
    chown root:$csvnUser $csvnPath/csvn/lib/httpd_bind/httpd_bind
    chmod u+s $csvnPath/csvn/lib/httpd_bind/httpd_bind
    
    msg="启动CSVN"
    echo "`date "+%Y-%m-%d %H:%M:%S"` $msg" >>$logs_file
    echo -e "XXX\n90\n$msg\nXXX"
    echo 90
    /etc/init.d/csvn start >>$logs_file 2>&1
    kill `ps aux |grep $csvnPath/csvn/bin/httpd|grep -v grep|awk '{print $2}'` >/dev/null 2>&1
    /etc/init.d/csvn-httpd start >>$logs_file 2>&1
    
    echo -e "XXX\n100\ndone！！！\nXXX"
    echo 100
    sleep 1 
    } | whiptail --backtitle "Author: Elvis" --title "安装csvn" --gauge " " 6 60 0
    if [ -f /tmp/.csvn.err.info ];then
        errinfo=`cat /tmp/.csvn.err.info` >>$logs_file
        rm -rf /tmp/.csvn.err.info
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "csvn安装失败！\n$errinfo" 10 70
        sleep 0.10
        return 1
    fi
    #判断是否启动
    sleep 0.30
    UserUID=`cat /etc/passwd|grep "^$csvnUser:"|awk -F":" '{print $3}'`
    pass_info=
    if [ -n "$UserUID" -a "$csvnUser" != "root" ];then
        pass_info="$csvnUser用户密码为：$csvnUserPw，请牢记或修改！"
    fi
    
    csvn_control_status=`ps aux |grep wrapper|grep java|grep $csvnUser|grep $csvnPath/csvn/bin|grep -v grep`
    if [ "$PortCheck" == "Yes" ];then
        csvn_status=`$listen_cmd |grep ":$csvnPort "`
    else
        csvn_status=`ps aux |grep "$csvnPath/csvn/bin/httpd -f "|grep -v grep`
    fi
    svnURL=
    if [ "$csvnPort" == "443" ];then
        svnURL="https://$ipaddr/svn"
    else
        svnURL="https://$ipaddr:$csvnPort/svn"
    fi
    
    if [[ -n $csvn_control_status && -n $csvn_status ]];then
        echo "csvn安装成功" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "消息" --msgbox "csvn安装成功！！！\n管理控制台地址：http://$ipaddr:$csvnPort_control/csvn\n默认管理用户密码为：admin/admin\nSVN地址：$svnURL\n$pass_info" 13 80
    elif [[ -n $csvn_control_status && -z $csvn_status ]];then
        echo "csvn控制台服务启动成功，SVN服务启动失败，请检查端口或者权限" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "警告" --msgbox "csvn管理服务启动成功，SVN服务启动失败\n管理控制台地址：http://$ipaddr:$csvnPort_control/csvn\n默认管理用户密码为：admin/admin\n请使用$csvnPath/csvn/bin/csvn-httpd start命令启动SVN服务以排查错误\n$pass_info" 13 80
    else
        echo "csvn安装失败" >>$logs_file
        whiptail --backtitle "Author: Elvis" --title "错误" --msgbox "csvn安装失败！！！\n请使用$csvnPath/csvn/bin/csvn start启动管理服务以排查错误" 10 70
    fi
    sleep 0.30 
}